package edu.controller;

import edu.service.NoticeService;
import edu.vo.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/notices")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    /**
     * 保存通知信息
     * @param notice 通知对象
     * @return 保存后的通知对象
     */
    @PostMapping
    public ResponseEntity<Notice> saveNotice(@RequestBody Notice notice) {
        Notice savedNotice = noticeService.saveNotice(notice);
        return new ResponseEntity<>(savedNotice, HttpStatus.CREATED);
    }

    /**
     * 根据ID获取通知信息
     * @param id 通知ID
     * @return 通知对象的Optional包装
     */
    @GetMapping("/{id}")
    public ResponseEntity<Notice> getNoticeById(@PathVariable Integer id) {
        Optional<Notice> notice = noticeService.getNoticeById(id);
        return notice.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 获取所有通知信息
     * @return 通知列表
     */
    @GetMapping
    public ResponseEntity<List<Notice>> getAllNotices() {
        List<Notice> notices = noticeService.getAllNotices();
        return new ResponseEntity<>(notices, HttpStatus.OK);
    }

    /**
     * 根据ID删除通知信息
     * @param id 通知ID
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteNoticeById(@PathVariable Integer id) {
        noticeService.deleteNoticeById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 更新通知信息
     * @param id 通知ID
     * @param notice 新的通知信息
     * @return 更新后的通知对象
     */
    @PutMapping("/{id}")
    public ResponseEntity<Notice> updateNotice(@PathVariable Integer id, @RequestBody Notice notice) {
        Notice updatedNotice = noticeService.updateNotice(id, notice);
        return updatedNotice != null ? new ResponseEntity<>(updatedNotice, HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}